/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.bemanager;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inspur.edp.bef.bemanager.util.BefFileUtil;
import com.inspur.edp.bef.bizentity.BeThreadLocal;
import com.inspur.edp.bef.bizentity.Context;
import com.inspur.edp.bef.bizentity.GspBusinessEntity;
import com.inspur.edp.lcm.metadata.api.IMetadataContent;
import com.inspur.edp.lcm.metadata.api.service.FileService;
import com.inspur.edp.lcm.metadata.spi.MetadataContentSerializer;
import com.inspur.edp.bef.bizentity.Context;
import com.inspur.edp.bef.bizentity.BeThreadLocal;
import java.io.IOException;
import java.io.File;
import java.nio.file.Paths;

public class ContentSerializer implements MetadataContentSerializer {

  @Override
  public JsonNode Serialize(IMetadataContent iMetadataContent) {
    Context context = new Context();
    context.setfull(false);
    BeThreadLocal.set(context);
    ObjectMapper mapper = new ObjectMapper();

    try {
      String jsonResult = mapper.writeValueAsString((GspBusinessEntity) iMetadataContent);
      JsonNode jsonNode = mapper.readTree(jsonResult);
      return jsonNode;
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage());
    } finally {
      BeThreadLocal.unset();
    }
  }

  @Override
  public IMetadataContent DeSerialize(JsonNode jsonNode) {
    ObjectMapper mapper = new ObjectMapper();
    try {
      return mapper.readValue(handleJsonString(jsonNode.toString()), GspBusinessEntity.class);
    } catch (IOException | RuntimeException e) {
      throw new RuntimeException("Be元数据反序列化失败！", e);
//			e.printStackTrace();
//			writeLog("Be序列化失败：" + jsonNode.toString());
    }
//		return null;
  }

  private void writeLog(String text) {
    FileService fileService = BefFileUtil.getService(FileService.class);
//		String devPath = fileService.getDevRootPath();
//		String path = devPath + "\\jstack\\log\\";
    // 添加没有资源文件报空指针的问题
    if (this.getClass().getResource(File.separator + "BefProjectMavenDependency.xml") == null) {
      return;
    }
    String path =
        this.getClass().getResource(File.separator + "BefProjectMavenDependency.xml").toString()
            .split(":file:" + File.separator)[1].split(
            File.separator + "platform")[0] +
            File.separator + "log" + File.separator;
    String fileName = "BefSerializerLog.txt";
    if (!fileService.isFileExist(path + fileName)) {
      try {
        fileService.createFile(path, fileName);
      } catch (IOException e) {
      }
    }
    fileService.fileUpdate(path + fileName, text);
  }

  private static String handleJsonString(String contentJson) {
    if (contentJson.startsWith("\"")) {
      contentJson = contentJson.replace("\\\"", "\"");
      while (contentJson.startsWith("\"")) {
        contentJson = contentJson.substring(1, contentJson.length() - 1);
      }
    }
    return contentJson;
  }
}
